package com.bdqn.easybuy1.servlet.backend;

import com.bdqn.easybuy1.entities.News;
import com.bdqn.easybuy1.param.NewsParams;
import com.bdqn.easybuy1.service.news.NewsService;
import com.bdqn.easybuy1.service.news.NewsServiceImpl;
import com.bdqn.easybuy1.servlet.AbstractServlet;
import com.bdqn.easybuy1.utils.EmptyUtils;
import com.bdqn.easybuy1.utils.Pager;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet(name = "AdminNewsServlet", value = "/admin/news")
public class AdminNewsServlet extends AbstractServlet {

    private NewsService newsService;

    @Override
    public void init() throws ServletException {
        newsService = new NewsServiceImpl();
    }

    /**
     * 查询新闻详情
     *
     * @param request
     * @param response
     * @return
     */
    public String newsDetail(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = request.getParameter("id");
        News news = newsService.findNewsById(id);
        request.setAttribute("news", news);
        request.setAttribute("menu", 7);
        return "/backend/news/newsDetail";
    }

    /**
     * 查询新闻列表
     *
     * @param request
     * @param response
     * @return
     */
    public String queryNewsList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取当前页数
        String currentPageStr = request.getParameter("currentPage");
        //获取页大小
        String pageSize = request.getParameter("pageSize");
        int rowPerPage = EmptyUtils.isEmpty(pageSize) ? 10 : Integer.parseInt(pageSize);
        int currentPage = EmptyUtils.isEmpty(currentPageStr) ? 1 : Integer.parseInt(currentPageStr);
        int total = newsService.queryNewsCount(new NewsParams());

        Pager pager = new Pager(total, rowPerPage, currentPage);
        pager.setUrl("/admin/news?action=queryNewsList");
        NewsParams params = new NewsParams();
        params.openPage((pager.getCurrentPage() - 1) * pager.getRowPerPage(), pager.getRowPerPage());
        List<News> newsList = newsService.queryNewsList(params);
        request.setAttribute("newsList", newsList);
        request.setAttribute("pager", pager);
        request.setAttribute("menu", 7);
        return "/backend/news/newsList";
    }
}
